package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService service;

    private UserBean loginUser;

    /**
     * 登录
     *
     * @param userName 用户名
     * @param passWord 密码
     * @return 登录对象
     */
    @RequestMapping("login")
    public String login(String userName, String passWord, HttpServletRequest req) {
        UserBean user = service.login(userName, passWord);
        loginUser = user;
        if (user != null) {
            req.getSession().setAttribute("loginUser", user);
            return "OK";
        } else {
            return "NO";
        }
    }

    /**
     * 通过id查询用户
     *
     * @param id 用户id
     * @return 用户对象
     */
    @RequestMapping("findById")
    public UserBean findById(Integer id) {
        return service.findById(id);
    }

    /**
     * 通过id修改密码
     *
     * @param id       用户id
     * @param passWord 新密码
     * @return 修改成功
     */
    @RequestMapping("updatePwd")
    public String updatePassWord(Integer id, String passWord) {
        service.updatePassWord(id, passWord);
        return "OK";
    }

    /**
     * 添加用户
     *
     * @return OK 添加成功 ；NO 添加失败
     */
    @RequestMapping("add")
    public String addUser(String userName,String name,String grade) {
        UserBean userBean = new UserBean(userName,name,grade);
        boolean c = service.addUser(userBean);
        if (c) {
            return "OK";
        } else {
            return "NO";
        }
    }

    /**
     * 查询所有用户
     *
     * @return 用户集合
     */
    @RequestMapping("findAll")
    public List<UserBean> findAll() {
        List<UserBean> user = service.findAll();
        return user;
    }

    /**
     * 删除用户
     *
     * @param id  用户id
     * @return 删除成功返回 OK；删除失败返回 NO
     */
    @RequestMapping("del")
    public String delUser(Integer id) {
        if (service.delUser(id, loginUser)) {
            return "OK";
        } else {
            return "NO";
        }
    }

    /**
     * 修改用户等级
     *
     * @param id    用户id
     * @param grade 修改后的等级
     * @return "OK"
     */
    @RequestMapping("updateGrade")
    public String updateGrade(Integer id, String grade) {
        service.updateUserGrade(id, grade);
        return "OK";
    }

    @RequestMapping("getUser")
    public UserBean getUser(HttpServletRequest req) {
        UserBean user = (UserBean) req.getSession().getAttribute("loginUser");
        System.out.println(user);
        return user;
    }
}
